package com.itheima.controller.system.user;


import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.Dept;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.utils.BeanUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/system/user/*")
public class UserServlet extends BaseServlet {

    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws Exception{

        String page = req.getParameter("page");
        String pageSize = req.getParameter("pageSize");

        List<User> userList= userService.findAll(page,pageSize);

        PageInfo<User> userPageInfo = new PageInfo<>(userList);
        req.setAttribute("page",userPageInfo);

        req.getRequestDispatcher("/pages/system/user/list.jsp").forward(req,resp);
    }


    private void list(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

      List<Dept> deptlist=userService.findAll1();

      req.setAttribute("deptList",deptlist);


        req.getRequestDispatcher("/pages/system/user/add.jsp").forward(req,resp);

    }
    private void save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        User user = BeanUtil.fillBean(req, User.class, "yyyy-MM-dd");
        userService.save(user);

        findAll(req,resp);
    }


    private void findById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String id = req.getParameter("id");
        User user=userService.findById(id);

        List<Dept> deptlist=userService.findAll1();

        req.setAttribute("deptList",deptlist);



        req.setAttribute("user",user);


        req.getRequestDispatcher("/pages/system/user/update.jsp").forward(req,resp);

    }


    private void edit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        User user = BeanUtil.fillBean(req, User.class, "yyyy-MM-dd");
        userService.edit(user);
        findAll(req,resp);
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String id = req.getParameter("id");
        userService.delete(id);

        findAll(req,resp);



    }
}
